﻿using BLL.Sys;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NLog;
using SFL;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using Web.Models;

namespace Web.Controllers
{
    public class HomeController:Controller
    {
        //定义一记录日志的容器
        //protected static Logger Logger = LogManager.GetCurrentClassLogger();

        [AllowAnonymous]
        public IActionResult Index()
        {
            return View();
        }

        [AllowAnonymous]
        public IActionResult Login(string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            return View();
        }
                
        [HttpPost, AllowAnonymous]
        public async Task<IActionResult> Login(LoginModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            var ip = HttpContext.Connection.RemoteIpAddress.ToString();

            if (ModelState.IsValid)
            {
                UserService _us = new UserService();
                //检查用户信息
                var user = _us.CheckUser(model.LoginId, model.Password);
                if (user != null)
                {
                    if (user.IsLock)
                    {
                        ViewBag.ErrorInfo = "用户不存在或已被锁定。";
                        return View();
                    }

                    //根据user.roleid获取用户所对应的角色
                    RoleService _rs = new RoleService();
                    var role = _rs.GetEntityById(user.RoleId);

                    var userIdentity = new ClaimsIdentity(role.Name);   // 指定身份认证类型(登录的是什么角色)

                    userIdentity.AddClaim(new Claim(ClaimTypes.Role, role.Code));  //获取角色编码，用于在控制器上使用
                    userIdentity.AddClaim(new Claim(ClaimTypes.Name, user.Id.ToString()));  // 用户名称，以用户Id代替，因为NavigationViewComponent.cs中只能获取到User.Identity.Name
                    userIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserName));    // 用户姓名

                    var userPrincipal = new ClaimsPrincipal(userIdentity);

                    //创建Cookie保存自己的信息，必须要初始化一个ClaimsPrincipal（类型）来序列化和保存你想保存的用户信息到Cookie中。
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal,
                        new AuthenticationProperties
                        {
                            ExpiresUtc = DateTime.UtcNow.AddMinutes(240),
                            IsPersistent = false,
                            AllowRefresh = false
                        });
                                                         
                    Log.WriteLog(user.UserName + "(" + user.LoginId + ")登录成功。登录IP:" + ip);

                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return Redirect("/Sys/Home/Index");
                    }

                    //记录Session
                    //HttpContext.Session.SetString("CurrentUserId", user.Id.ToString());
                    //HttpContext.Session.SetString("CurrentUserName", user.UserName);
                    //HttpContext.Session.Set("CurrentUser", Utility.ByteConvertHelper.Object2Bytes(user));
                    //跳转到系统首页
                    //return RedirectToAction("Index", "Home");
                }
                Log.WriteLog(model.LoginId + "(" + model.Password + ")登录失败。登录IP:" + ip);
                ViewBag.ErrorInfo = "用户名或密码错误。";
                return View();
            }
            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    ViewBag.ErrorInfo = item.Errors[0].ErrorMessage;
                    break;
                }
            }
            return View(model);
        }

        public async Task<IActionResult> Logout()
        {
            //退出当前用户的登录，删除登录的cookie信息
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            //HttpContext.Session.Clear();
            return RedirectToAction("/");
        }

        public IActionResult OtherGzh()
        {
            return View();
        }

        public IActionResult YY()
        {
            return View();
        }
    }
}
